/*
 * Copyright (c) 2009 Skyon Technology Ltd.
 * All rights reserved.
 *
 * project: eroad-daemon
 * create: 2009-5-5 ����09:30:33
 * cvs: $Id: BuildFile.java,v 1.1 2010/11/24 07:46:12 dev_cvs Exp $
 */
package cn.batch.daemon.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.batch.daemon.exception.FileHandelException;

/**
 * 写入文件类.
 * 
 * @author liuning
 * @version $Revision: 1.1 $
 */
public class BuildFile {

	private static final Log logger = LogFactory.getLog(BuildFile.class);

	private PrintWriter writer = null;
	
	/**
	 * 构造函数
	 * 
	 * @param filePath 文件路径
	 * @param isNeedHead 是否需要文件头
	 * @param header 文件头内容
	 */
	public BuildFile(String filePath, boolean isNeedHead, String header) {
		File f = new File(filePath);
		try {
			File parentFile = f.getParentFile();
			if (!parentFile.exists()) {
				parentFile.mkdirs();
			}
			if (!f.exists()) {
				f.createNewFile();
			}

			writer = new PrintWriter(new BufferedWriter(new FileWriter(f)));
			
			if (isNeedHead) {
				writeLine(header);
			}
		} catch (IOException e) {
			logger.error("获取文件写入流异常", e);
			throw new FileHandelException("获取文件写入流异常", e);
		}
	}

	/**
	 * 把字符串写入文件作为一行
	 * @param line
	 */
	public void writeLine(String line) {
		if (writer != null) {
			writer.println(line);
		}
	}

	/**
	 * 关闭文件writer流
	 */
	public void closeWriter() {
		if (writer != null) {
			writer.close();
		}
	}

	public static void main(String[] args) throws IOException {

		BuildFile bf = new BuildFile("c:/test/foo.txt",false,null);

		for (int i = 0; i < 5000000; i++) {
			bf.writeLine("第" + i + "行");

			if (i % 100000 == 0) {
				System.out.println(i);
			}
		}
		bf.closeWriter();
	}
}
